from flask import Flask, render_template,request, url_for
import pandas as pd
import plotly.express as px
import numpy as np
import plotly as py
import plotly.graph_objs as go


app = Flask(__name__)

def read_data():
    df = pd.read_csv('bestsellers with categories.csv',encoding='utf-8')

    return df


@app.route("/welcome")
def all():
    df = read_data()
    # 以虚构与非虚构
    df_fiction = df[df['Genre'] == 'Fiction'].count().sum()
    df_non_fiction = df[df['Genre'] == 'Non Fiction'].count().sum()
    df_fiction
    df_non_fiction

    # 绘制饼图
    labels = ['虚构', '非虚构']
    values = [df_fiction, df_non_fiction]
    fig = go.Figure(data=[go.Pie(labels=labels, values=values)])

    py.offline.plot(fig, filename="亚马逊图书.html", auto_open=False)
    with open("亚马逊图书.html", encoding="utf8", mode="r") as f:
        plot_all1 = "".join(f.readlines())

    return render_template(
        "welcome.html",
        tu=plot_all1
            )

@app.route('/Author')
def Author():
    df = read_data()
    # 以价格为单位对作者进行排序
    new_df = df.groupby('Author').mean().reset_index().sort_values('Price', ascending =False).head(10)
    data = [go.Bar(x=new_df['Author'], y=new_df['Price'])]
    layout = go.Layout(template='plotly_dark', title='书价最高的十大畅销书作者')
    fig = go.Figure(data=data, layout=layout)
    py.offline.plot(fig, filename="以作者为单位的价格比较.html", auto_open=False)
    with open("以作者为单位的价格比较.html", encoding="utf8", mode="r") as f:
        plot_all2 = "".join(f.readlines())

    # 以书的数量为排序
    new_df = df.groupby('Author').count().reset_index().sort_values('Name', ascending=False).head(10)
    data = [go.Bar(x=new_df['Author'], y=new_df['Name'])]
    layout = go.Layout(template='plotly_dark', title='畅销书数量最多的前10位作者 ')
    fig = go.Figure(data=data, layout=layout)
    py.offline.plot(fig, filename="以作者为单位的数量比较.html", auto_open=False)
    with open("以作者为单位的数量比较.html", encoding="utf8", mode="r") as f:
        plot_all3 = "".join(f.readlines())

    # 以评论数为排序
    new_df = df.groupby('Author').mean().reset_index().sort_values('Reviews', ascending=False).head(10)
    data = [go.Bar(x=new_df['Author'], y=new_df['Reviews'])]
    layout = go.Layout(template='plotly_dark', title='前10位拥有最高评论的畅销书作者')
    fig = go.Figure(data=data, layout=layout)
    py.offline.plot(fig, filename="以作者为单位的评论比较.html", auto_open=False)
    with open("以作者为单位的评论比较.html", encoding="utf8", mode="r") as f:
        plot_all4 = "".join(f.readlines())


    return render_template(
        "Author.html",
        tu2=plot_all2,
        tu3=plot_all3,
        tu4=plot_all4,
    )


@app.route('/genre', methods=['GET', 'POST'])
def genrer():
    df = read_data()
    # 按照虚构与非虚构类型分类
    new_df1 = df[df['Genre'] == 'Fiction']
    new_df2 = df[df['Genre'] == 'Non Fiction']
    trace0 = go.Bar(x=new_df1['Year'], y=new_df1['Price'], name='Fiction')
    trace1 = go.Bar(x=new_df2['Year'], y=new_df2['Price'], name='Non_Fiction')
    data = [trace0, trace1]
    layout = go.Layout(title='近年按照虚构与非虚构来划分的书籍价格', barmode='group')
    fig = go.Figure(data=data, layout=layout)

    py.offline.plot(fig, filename="近年按照虚构与非虚构来划分的书籍价格.html", auto_open=False)
    with open("近年按照虚构与非虚构来划分的书籍价格.html", encoding="utf8", mode="r") as f:
        plot_all5 = "".join(f.readlines())

    trace0 = go.Bar(x=new_df1['Year'], y=new_df1['Reviews'], name='虚构')
    trace1 = go.Bar(x=new_df2['Year'], y=new_df2['Reviews'], name='非虚构')
    data = [trace0, trace1]
    layout = go.Layout(title='近年按照虚构与非虚构来划分的评论数量', barmode='stack')
    fig = go.Figure(data=data, layout=layout)
    plot_all6 = "".join(f.readlines())


    return render_template(
        "genre.html",
        tu5=plot_all5,
        tu6=plot_all6,
    )



if __name__ == '__main__':
    app.run(debug=True)
